package com.zjsos.daoinstance;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import com.zjsos.dao.BaseDao;
import com.zjsos.dao.BaseServiceImpl;
import com.zjsos.db.hibernate.LocalSessionFactoryBeanBuilder;
/**
 * 初始化一个默认SessionFactory
 * @Author sharlot2050@foxmail.com
 * @Date 2019年8月26日
 * @Version 1.00
 */
@Configuration
@ConditionalOnProperty(name = "GOdata.database.datasource-for-casm.url")
public class LocalSessionFactoryConfigForCasm {

	@Bean("dataSourcePropertiesForCasm")
	@ConfigurationProperties(prefix = "GOdata.database.datasource-for-casm")
	public DataSourceProperties dataSourcePropertiesForCasm() {
		return new DataSourceProperties();
	};

	@Bean("jpaPropertiesForCasm")
	@ConfigurationProperties(prefix = "GOdata.database.jpa-for-casm")
    @DependsOn("dataSourcePropertiesForCasm")
	public JpaProperties jpaPropertiesForCasm() {
		return new JpaProperties();
	}
	    
    @Bean("sessionFactoryForCasm")
    @DependsOn({"dataSourcePropertiesForCasm", "jpaPropertiesForCasm"})
    public LocalSessionFactoryBean sessionFactoryForCasm() throws Exception {
        return new LocalSessionFactoryBeanBuilder(dataSourcePropertiesForCasm(), jpaPropertiesForCasm()).create();
    }
    
    @Bean("casmDbServiceImpl")
    @DependsOn("sessionFactoryForCasm")
	public BaseServiceImpl casmDbServiceImpl() throws Exception{

		BaseDao hibernateBaseDao = new BaseDao();
		hibernateBaseDao.setSessionFactory(sessionFactoryForCasm().getObject());
		BaseServiceImpl anotherDbServiceImpl = new BaseServiceImpl();
		anotherDbServiceImpl.setBaseDao(hibernateBaseDao);
		return anotherDbServiceImpl;
	}

	@Bean("platformTransactionManagerForCasm")
    @DependsOn("sessionFactoryForCasm")
    public PlatformTransactionManager platformTransactionManager() throws Exception {
    	HibernateTransactionManager transactionManager = new HibernateTransactionManager();
		transactionManager.setSessionFactory(sessionFactoryForCasm().getObject());
		return transactionManager;
    }
}
